#include	"../core/storage.h"

extern "C" {
#include	<luajit.h>
#include	<lualib.h>
#include	<lauxlib.h>
}

namespace {

    static int Get(lua_State * lua) {
        const char * key = lua_tostring(lua, 1);
        std::string val;
        if (Storage::Instance().TryGet(key, val)) {
            lua_pushlstring(lua, val.data(), val.size());
            return 1;
        } else {
            return 0;
        }
    }

    static int Set(lua_State * lua) {
        const char * key = lua_tostring(lua, 1);
        size_t len = 0;
        const char * val = lua_tolstring(lua, 2, &len);
        bool never_expire = lua_gettop(lua) > 2 ? lua_toboolean(lua, 3) == 1 : false;
        Storage::Instance().Set(key, std::string(val, len), never_expire);
        return 0;
    }
}

void RegisterApi_Storage(lua_State * lua) {
    lua_newtable(lua);

	lua_pushcfunction(lua, &Get);
	lua_setfield(lua, -2, "get");

	lua_pushcfunction(lua, &Set);
	lua_setfield(lua, -2, "set");

	lua_setglobal(lua, "storage");
}
